using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;

using Tulde.Core;
using Tulde.MP3tunes;
using Tulde.MP3tunes.Model;
using Tulde.MP3tunes.Model;

namespace MP3tunes.LockerPlayer
{
    public partial class MainPage : PhoneApplicationPage
    {
        public App CurrentApp
        {
            get
            {
                return App.Current as App;
            }
        }

        private DefaultCredentials credentials;
        private ShellTileUpdateService s = new ShellTileUpdateService();


        // ConstructorTulde.MP3tunes.Mp3TunesMusicService
        public MainPage()
        {
            InitializeComponent();
#if DEBUG
            this.credentials = new DefaultCredentials
            {
                UserName = "jason.tully@gmail.com",
                Password = "jason123"
            };
#endif

            // Set the data context of the listbox control to the sample data
            // DataContext = App.ViewModel;
            Mp3TunesMusicService.Error += new EventHandler<DataServiceEventArgs>(Mp3TunesMusicService_Error);
            this.Loaded += new RoutedEventHandler(MainPage_Loaded);
            this.pivotControl.Items.Remove(this.videos);
           // this.videos.Visibility = System.Windows.Visibility.Collapsed;
        }

        void Mp3TunesMusicService_Error(object sender, DataServiceEventArgs e)
        {
            MessageBox.Show(e.Message, e.Title ?? "Notification", MessageBoxButton.OK);
        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            if( SecurityProvider.IsAuthenticated)
            {

                this.ValidateCache();
            }
        }

        void credControl_Saved(object sender, UserControls.CredentialsEventArgs e)
        {
            this.UpdateShellIcon();
            this.credControl.Visibility = System.Windows.Visibility.Collapsed;
            this.pivotControl.Visibility = System.Windows.Visibility.Visible;
            this.ValidateCache();
        }

        


        // Load data for the ViewModel Items
        private void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            this.ToggleProgressBar(false);
            this.pivotControl.LoadingPivotItem-=new EventHandler<PivotItemEventArgs>(this.Pivot_LoadingPivotItem);
            
          


            if (System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable())
            {
              this.credControl.Saved += new EventHandler<UserControls.CredentialsEventArgs>(credControl_Saved);

                this.artistList.SelectionChanged -= new SelectionChangedEventHandler(artistList_SelectionChanged);
               
                if (!SecurityProvider.IsAuthenticated)
                {
                    this.credentials = this.credentials ?? (DefaultCredentials)SecurityProvider.LoadCredentials();
                    if (this.credentials == null)
                    {
                        this.pivotControl.Visibility = System.Windows.Visibility.Collapsed;
                        this.credControl.Visibility = System.Windows.Visibility.Visible;

                
                    }
                    else
                    {
                        this.credControl.Visibility = System.Windows.Visibility.Collapsed;
                        this.pivotControl.Visibility = System.Windows.Visibility.Visible;
                        this.ToggleProgressBar(true);
                        this.Authenticate();
                    }
                }
                else
                {
                    this.ToggleProgressBar(true);
                    this.LoadArtists();
                }
            }
            else
            {

            }
             
        }
        private void UpdateShellIcon()
        {
            if (!SettingsProvider.Settings.EnablePNS && !SettingsProvider.Settings.SuppressEnablePNSDialog)
            {
                MessageBoxResult result = MessageBox.Show(Settings.GetOptInMessage(), "User Action Required", MessageBoxButton.OKCancel);
                if (result == MessageBoxResult.Cancel)
                {
                    SettingsProvider.Settings.EnablePNS = false;
                }
                else if (result == MessageBoxResult.OK)
                {
                    SettingsProvider.Settings.EnablePNS = true;
                    s.GetLatestAlbumArt();
                }
                SettingsProvider.Settings.SuppressEnablePNSDialog = true;
                SettingsProvider.Save();

            }
          
        }
        private void Authenticate()
        {
            Tulde.MP3tunes.Mp3TunesMusicService.Authenticate(this.credentials, token =>
            {
                this.statusMessage.Text = "Logging In.";
                SecurityProvider.SetAuthenticationTokens(token);
                //schedule a shell update for the live tile
                this.UpdateShellIcon();
                //now lets get the last update checksum to see if we need to invalidate our cache.
                ValidateCache();
              
             
           
            });
        }

        private void ValidateCache()
        {
            this.ToggleProgressBar(true);
            Mp3TunesMusicService.GetLastUpdate(x =>
            {
              
                this.statusMessage.Text = "Checking for data updates.";
                if (ViewModelCacheFactory.Instance.CacheItemExists("checksum"))
                {
                    Checksum cached = StorageProviderFactory.Instance.Read<Checksum>("checksum");
                    if (cached.Timestamp != x.Timestamp)
                    {
                        ViewModelCacheFactory.Instance.SetCacheItem<Checksum>("checksum", x);
                        ViewModelCacheFactory.Instance.Invalidate();
                        this.statusMessage.Text = "Downloading Locker data.";
                        Mp3TunesMusicService.DownloadLockerData(y =>
                        {
                            this.CurrentApp.ViewModelCache = y;
                            this.statusMessage.Text = "";
                            this.artistList.DataContext = y.Artists;
                            //this.LoadArtists();
                        });
                    }
                    else
                    {
                        this.statusMessage.Text = "No updates found.";
                        //this.LoadArtists();
                        this.artistList.DataContext = this.CurrentApp.ViewModelCache.Artists;
                    }
                }
                else
                {

                    StorageProviderFactory.Instance.Save("checksum", x);
                    this.statusMessage.Text = "Downloading Locker data.";
                    Mp3TunesMusicService.DownloadLockerData(y =>
                    {
                        this.CurrentApp.ViewModelCache = y;
                        this.statusMessage.Text = "";
                        this.artistList.DataContext = y.Artists;
                    });
                }


            });
        }

        

        private void Pivot_LoadingPivotItem(object sender, PivotItemEventArgs e)
        {
            this.ToggleProgressBar(true);
            switch (e.Item.Name)
            {
                //case "artists": this.LoadArtists(); break;
                case "albums": this.LoadAlbums(); break;
                case "playlists": this.LoadPlaylists(); break;
                case "videos": this.LoadVideos(); break;
                default: this.ToggleProgressBar(false); break;
            }
        }

        #region Load Pivot Item Methods
        private void LoadArtists()
        {
            this.pivotControl.LoadingPivotItem -= new EventHandler<PivotItemEventArgs>(this.Pivot_LoadingPivotItem);
            this.artistList.SelectionChanged-=new SelectionChangedEventHandler(artistList_SelectionChanged);
            Tulde.MP3tunes.Mp3TunesMusicService.EnumerateArtists(list =>
            {
                this.artistList.DataContext = list.Artists;
                this.pivotControl.LoadingPivotItem += new EventHandler<PivotItemEventArgs>(this.Pivot_LoadingPivotItem);
                this.ToggleProgressBar(false);
                this.artistList.SelectionChanged += new SelectionChangedEventHandler(artistList_SelectionChanged);
              
                this.ShowEmptyMessage<Artist>("No Artists Found.",list.Artists,"artists");
               
            });
          
        }
        private void LoadAlbums()
        {
            Tulde.MP3tunes.Mp3TunesMusicService.EnumerateAlbums(list =>
            {
                this.listAlbums.DataContext = list.Albums;
                this.ToggleProgressBar(false);
                this.ShowEmptyMessage<Album>("No Albums Found.", list.Albums,"albums");
             
            });
        }
        private void LoadPlaylists()
        {
            Tulde.MP3tunes.Mp3TunesMusicService.EnumeratePlaylists(list =>
            {

                this.playlistList.DataContext = list.Playlists;
                this.ToggleProgressBar(false);
                this.ShowEmptyMessage<Playlist>("No Playlists Found.", list.Playlists,"playlists");
                
            });
        }
        private void LoadVideos()
        {
            //video
            Tulde.MP3tunes.Mp3TunesMusicService.EnumerateVideos(list =>
            {

                this.videoList.DataContext = list.Tracks;
                this.ToggleProgressBar(false);
                this.ShowEmptyMessage<Track>("No Videos Found.", list.Tracks,"videos");
                
            });
        }
        #endregion
        private void NavigateToTracks()
        {
            Album album = this.listAlbums.SelectedItem as Album;
            if( album != null)
                NavigationService.NavigateWithViewModels("/Pages/MediaPlayer.xaml", album);

        }
        private void listAlbums_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            this.NavigateToTracks();
        }
        private void artistList_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {

            Artist artist = this.artistList.SelectedItem as Artist;
            if( artist != null)
             NavigationService.NavigateWithViewModels("/Pages/AlbumPage.xaml", artist);
        }

        private void playlistList_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            Playlist playlist = this.playlistList.SelectedItem as Playlist;
            if( playlist != null)
                NavigationService.NavigateWithViewModels("/Pages/MediaPlayer.xaml",playlist);
        }

        private void ToggleProgressBar(bool visible)
        {
            this.Dispatcher.BeginInvoke( new Action( ()=>{ this.statusProgress.IsIndeterminate = visible; } ) );
        }

        private void appMenu_OnNavigate(object sender, UserControls.AppMenuEventArg e)
        {
            if( !string.IsNullOrEmpty(e.Destination))
                this.NavigationService.NavigateWithViewModels(e.Destination);
        }

        private void videoList_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            Track video = this.videoList.SelectedItem as Track;
            if( video != null)
             this.NavigationService.NavigateWithViewModels("/Pages/VideoPlayer.xaml",video);
        }
        private void ShowEmptyMessage<T>(string message, List<T> items, string category)
        {
            if (items.Empty())
            {
                this.statusMessage.Text = message;

            }
            else
            {
                this.statusMessage.Text =  String.Format("Found {0} {1}",items.Count,category);
            }
        }
    }
}